package net.tv90.shoppingserver.controller;

import cn.dev33.satoken.stp.StpUtil;
import net.tv90.shoppingserver.model.domain.Good;
import net.tv90.shoppingserver.model.dto.GoodQueryDTO;
import net.tv90.shoppingserver.model.vo.CartVO;
import net.tv90.shoppingserver.service.CartService;
import net.tv90.shoppingserver.service.GoodService;
import net.tv90.shoppingserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.List;

@CrossOrigin
@Controller
public class StaticController {

    @Autowired
    UserService userService;

    @Autowired
    GoodService goodService;

    @Autowired
    CartService cartService;

    @GetMapping("/")
    public String index(Model model) {
        handleIndexModel(model);
        return "index";
    }

    @GetMapping("/index")
    public String index2(Model model) {
        handleIndexModel(model);
        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @GetMapping("/goods")
    public String goods(Model model) {
        handleIndexModel(model);
        return "goods";
    }

    @GetMapping("/cart")
    public String cart(Model model) {
        if (!StpUtil.isLogin()) {
            return "redirect:/login";
        }
        handleIndexModel(model);
        List<CartVO> list = cartService.getAllCartItems(StpUtil.getLoginIdAsInt());
        BigDecimal totalPrice = new BigDecimal(0);
        boolean canCalculate = true;
        for (CartVO cartVO : list) {
            totalPrice = totalPrice.add(cartVO.getGood().getPrice().multiply(new BigDecimal(cartVO.getNum())));
            if (cartVO.getGood().getStock() <= 0) {
                canCalculate = false;
            }
        }
        model.addAttribute("canCalculate", canCalculate);
        model.addAttribute("list", list);
        model.addAttribute("totalPrice", totalPrice);
        return "cart";
    }

    private void handleIndexModel(Model model) {
        String username = userService.getCurrentUserName();
        if (username != null) {
            model.addAttribute("username", username);
        }
        GoodQueryDTO goodQueryDTO = new GoodQueryDTO();
        goodQueryDTO.setPage(1);
        goodQueryDTO.setPageNum(12);
        goodQueryDTO.setDesc(1);
        goodQueryDTO.setOrderBy("name");
        List<Good> goodList = goodService.queryGoods(goodQueryDTO);
        int num = goodService.queryNum(goodQueryDTO);
        model.addAttribute("goods", goodList);
        model.addAttribute("num", num);
        model.addAttribute("dto", goodQueryDTO);
    }
}
